home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 17712 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.5 KB

  1. Path: grimsel.zurich.ibm.com!usenet
  2. From: Keith Whittingham <wgk@zurich.ibm.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: HELP Borland C++ 5.0 pointer problem
  5. Date: Wed, 17 Apr 1996 09:44:52 -0700
  6. Organization: IBM Zurich Research Laboratory
  7. Message-ID: <31752004.62B1@zurich.ibm.com>
  8. References: <4klke8$7mb@dub-news-svc-2.compuserve.com> <316e9fdb.457757@10.0.2.1> <317409DC.59B@ids2.idsonline.com>
  9. NNTP-Posting-Host: pine.zurich.ibm.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.01 (Win16; I)
  14.  
  15. Lally Singh wrote:
  16. >> 
  17. > char * testfunction( char * inData)
  18. > {
  19. >         char * buffer = new[] char[20]; // allocates on the heap, remember to delete[] it!
  20. >         strcpy( buffer, inData );       // copy the string
  21. >         return buffer;                  // return the new buffer
  22. > };
  23.  
  24. Although that will work I would suggest that it's bad programming 
  25. practice: The function which allocates memory should be the
  26. function which deletes it. For instance if I decided that
  27. I could replace your function with one line...
  28.  
  29.   char *testfunction(char *inData)
  30.   {
  31.      return strdup(inData);
  32.   }
  33.  
  34. Which is perfectly valid (smaller, and works faster) then
  35. we have a problem. If the caller deletes the 
  36. memory we have a potential disaster on our hands.
  37. He should of course free() the block.
  38.  
  39. The solution? Either provide an allocation function and a deletion 
  40. function or have the caller pass you the ready allocated memory.
  41.  
  42.  
  43. -- 
  44. Keith Whittingham
  45. wgk@zurich.ibm.com
  46.